<template>
  <div class="profile-edit-container">
    <h3>编辑个人信息</h3>
    <el-form :model="userProfile" :rules="rules" ref="profileForm" label-width="100px" class="profile-edit-form">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userProfile.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userProfile.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userProfile.phone"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUserApi, updateUserProfileApi } from '../api/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const profileForm = ref(null)
const userProfile = ref({
  username: '',
  email: '',
  phone: ''
})

const rules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
})

const goBack = () => {
  router.back()
}

const submitForm = () => {
  profileForm.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateUserProfileApi(userProfile.value)
        ElMessage.success('个人信息更新成功')
        router.back()
      } catch (error) {
        ElMessage.error('更新失败，请重试')
      }
    } else {
      ElMessage.warning('请检查表单填写')
      return false
    }
  })
}

onMounted(async () => {
  try {
    const res = await getCurrentUserApi()
    userProfile.value = res.data
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
})
</script>

<style scoped>
.profile-edit-container {
  padding: 16px;
  max-width: 600px;
  margin: 0 auto;
}

.profile-edit-form {
  margin-top: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 